// pages/index/zone/goodsDetail/goodsDetail.js
import { axios } from '../../../utils/ajax.js'
import { checklogin } from '../../../utils/login.js'
let app = getApp()
let shareImg;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    title:'',
    //商品id
    goodsId: '',   //测试拼单用1214973
    //优惠券信息
    coupons:[],
    //是否有晒单
    comment: '',
    //轮播图信息
    album:[],
    data: {},
    //页面颜色尺码展示区域
    targetColor: [],
    targetSkusize: [],
    //可查资源处
    specData: [],
    //客服弹窗
    kefustate: false,
    //遮罩层状态
    maskstate: false,
    //购买弹窗
    goodsboxshow: false,
    //领券弹窗
    couponboxshow:false,
    //服务弹窗
    servicewindershow: false,
    //会员信息
    vipIntro:'',
    userid: '',
    token: '' ,
    //库存
    stock:'',
    //已经选择的颜色
    colorchecked:'',
    //已经选择的尺码
    skuchecked:'',
    //选择的数量
    nowstock: 1,
    //当前选中规格商品的库存
    checkedstock:'',
    //当前选中规格的id
    specId:'',
    //购物车数量
    cartnum:'',
    iPhoneX: false,
    //商品是否可以购买状态
    available: true,
    //拼单商品
    collage:[],
    //拼团结果弹窗
    groupresultbox: false,
    //弹窗的商品默认图片   轮播图的第一张
    defaultimg: '',
    //是否是拼团购买  0 普通购买    1 拼团购买
    isGroup: 0,
    //用户选择点击的购买类型   0 直接购买   1vip购买    2拼团购买
    buytype: 0,
    //商品弹窗顶部显示的价格  根据购买类型不同而改变
    goodsboxprice:'',
    //拼团广告
    grouplist:[],
    //广告滚动高度
    rollingtop: 0,
    isShow: true,
    //是否是会员
    isVip:false,
    //官方品鉴师
    qualityInfo: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options)
    let { linkId, title='' } = options
    this.setData({
      goodsId: linkId,
      title: title
    })
    
    this.calccartnum()

    //x适配
    console.log(app.globalData.model)
    if (app.globalData.model.substr(0, 8) == 'iPhone X') {
      this.setData({
        iPhoneX: true
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {


  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({
      isShow: true
    })

    let { userid = '', token = '' } = wx.getStorageSync('userinfo')
    this.setData({
      userid: userid,
      token: token,
      colorchecked: '',
      skuchecked: ''
    })
    axios({
      url: '/goods/detail',
      data: {
        goodsId: this.data.goodsId,
        userid: userid,
        token: token
      }
    }).then((res) => {
      console.log(res)
      this.setData({
        stock: res.data.stock ? res.data.stock : '',
        coupons: res.data.coupons ? res.data.coupons : [],
        collage: res.data.collage ? res.data.collage : [],
        qualityInfo: res.data.qualityInfo.level? res.data.qualityInfo : ''
      })
      //重新组合页面展示区域颜色规格数据结构
      let specShow = new Array(res.data.specShow.color.length)
      for (let i = 0; i < res.data.specShow.color.length; i++) {
        specShow[i] = {}
        specShow[i].val = res.data.specShow.color[i]
        specShow[i].cansell = true,
          specShow[i].checked = false
      }
      let skusize = new Array(res.data.specShow.skusize.length)
      for (let i = 0; i < res.data.specShow.skusize.length; i++) {
        skusize[i] = {}
        skusize[i].val = res.data.specShow.skusize[i]
        skusize[i].cansell = true
        skusize[i].checked = false
      }
      this.setData({
        album: res.data.album,
        defaultimg: res.data.album[0],
        data: res.data,
        targetColor: specShow,
        targetSkusize: skusize,
        specData: res.data.specData,
        comment: res.data.comment,
        title: res.data.goodsName,
        vipIntro: res.data.vipInfo,
        available: res.data.available,
        isVip: res.data.isVip,
      })
      console.log(this.data.specData)
      wx.setNavigationBarTitle({
        title: this.data.title
      })
      this.drawShareImg()
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    console.log('hide')
    this.setData({
      isShow: false
    })
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    console.log('onUnload')
    this.setData({
      isShow: false
    })
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  },

  /**
   * 用户点击右上角分享
   * 微信昵称+推荐+商品名称
   */
  onShareAppMessage: function (res) {
    console.log(this.data.title)
    let word = wx.getStorageSync('wxUserInfo') ? wx.getStorageSync('wxUserInfo').nickName + '推荐' : '';
    return {
      title: word+this.data.title,
      path: `/pages/home/goodsDetail/goodsDetail?linkId=${this.data.goodsId}`,
      imageUrl: shareImg
    }
  },
  //选择规格
  choosesku (e) {
    //重置用户选择数量
    this.setData({
      nowstock: 1
    })
    //如果可以购买 有库存
    if (e.currentTarget.dataset.cansell){
      let obj = this.data.targetColor
      let curarr = this.data.targetSkusize
      let index = e.currentTarget.dataset.index
      let choosesku = e.currentTarget.dataset.skusize
      if (curarr[index].checked) {
        curarr[index].checked = !curarr[index].checked
      } else {
        curarr.map(function (x) {
          x.checked = false
          return x.checked
        })
        curarr[index].checked = !curarr[index].checked
      }
      let result = curarr[index].checked ? this.data.specData.filter(x => x.skusize == choosesku) : this.data.specData
      let skubook = new Array(result.length)
      for (let i = 0; i < result.length; i++) {
        skubook[i] = result[i].color
      }
      obj.forEach((value, index) => {
        if (!skubook.includes(value.val)) {
          obj[index].cansell = false
        } else {
          obj[index].cansell = true
        }
      })
      this.setData({
        targetColor: obj,
        targetSkusize: curarr
      })
      this.setData({
        skuchecked: curarr[index].checked?curarr[index].val:''
      })
      console.log(this.data.skuchecked)
      this.changeimgprice()
    }
  },
  //根据选择规格的不同改变商品图和价格
  changeimgprice(){
    let specData = this.data.specData
    let result;
    //只有颜色 没有尺码
    if (this.data.targetColor.length && !this.data.targetSkusize.length){
      result = specData.find(x => x.color == this.data.colorchecked)
      this.setData({
        defaultimg: result.goodsImg ? result.goodsImg : this.data.album[0],
        goodsboxprice: this.data.buytype == 0 ? result.salePrice : (this.data.buytype == 1 ? result.vipPrice : result.groupPrice)
      })
    //只有尺码 没有颜色
    } else if (!this.data.targetColor.length && this.data.targetSkusize.length){
      result = specData.find(x => x.skusize == this.data.skuchecked)
      this.setData({
        defaultimg: result.goodsImg ? result.goodsImg : this.data.album[0],
        goodsboxprice: this.data.buytype == 0 ? result.salePrice : (this.data.buytype == 1 ? result.vipPrice : result.groupPrice)
      })
    //颜色尺码都有
    }else{
      //颜色尺码都选择的话
      if (this.data.colorchecked && this.data.skuchecked){
        result = specData.find(x => x.color == this.data.colorchecked && x.skusize == this.data.skuchecked )
        this.setData({
          defaultimg: result.goodsImg ? result.goodsImg : this.data.album[0],
          goodsboxprice: this.data.buytype == 0 ? result.salePrice : (this.data.buytype == 1 ? result.vipPrice : result.groupPrice)
        })
      }
    }
    console.log(result)
  },
  //选择颜色
  choosecolor (e) {
    //重置用户选择数量
    this.setData({
      nowstock:1
    })
    //如果可以购买 有库存
    if (e.currentTarget.dataset.cansell){
      let obj = this.data.targetSkusize
      let curarr = this.data.targetColor
      let index = e.currentTarget.dataset.index
      let choosecolor = e.currentTarget.dataset.color
      if (curarr[index].checked){
        curarr[index].checked = !curarr[index].checked
      }else{
        curarr.map(function (x) {
          x.checked = false
          return x.checked
        })
        curarr[index].checked = !curarr[index].checked
      }
      let result = curarr[index].checked ? this.data.specData.filter(x => x.color == choosecolor) : this.data.specData
      let colorbook = new Array(result.length)
      for (let i = 0; i < result.length; i++) {
        colorbook[i] = result[i].skusize
      }
      obj.forEach((value, index) => {
        if (!colorbook.includes(value.val)) {
          obj[index].cansell = false
        } else {
          obj[index].cansell = true
        }
      })
      this.setData({
        targetSkusize: obj,
        targetColor: curarr
      })
      this.setData({
        colorchecked: curarr[index].checked?curarr[index].val:''
      })
      console.log(this.data.colorchecked)
      this.changeimgprice()
    }
  },
  //三陪承诺
  onServiceTap (e) {
    console.log(e.currentTarget.dataset.linkId)
    wx.navigateTo({
      url: `/pages/webview/webview?linkId=${e.currentTarget.dataset.linkId}`,
    })
  },
  //打客服电话
  calltel (e) {
    console.log(e.currentTarget.dataset.tel)
    wx.makePhoneCall({
      phoneNumber: e.currentTarget.dataset.tel
    })
  },
  //关闭客服弹窗
  closekefu () {
    this.setData({
      kefustate: false,
      maskstate: false
    })
  },
  //打开客服弹窗
  openkefu () {
    this.setData({
      kefustate: true,
      maskstate: true
    })
  },
  //减法
  sub () {
    let nowstock = this.data.nowstock
    //如果有颜色未选择或者有规格未选择
    if ((this.data.targetColor.length ? !this.data.colorchecked : true) || (this.data.targetSkusize.length ? !this.data.skuchecked : true) ){
      wx.showToast({
        title: '请选择颜色或尺码',
        icon: "none"
      })
    }else{
      //获取选中规格的库存
      this.stockandspecid()
      if (nowstock > 1) {
        nowstock--
        this.setData({
          nowstock: nowstock
        })
      } else {
        wx.showToast({
          title: '一件起售',
          icon: "none"
        })
      }
    }
  },
  //加法
  add () {
    let nowstock = this.data.nowstock
    //如果有颜色未选择或者有规格未选择
    if ( (this.data.targetColor.length ? !this.data.colorchecked : true) || (this.data.targetSkusize.length ? !this.data.skuchecked : true) ) {
      wx.showToast({
        title: '请选择颜色或尺码',
        icon: "none"
      })
    } else {
      //获取选中规格的库存
      this.stockandspecid()
      if (nowstock < this.data.checkedstock) {
        nowstock++
        this.setData({
          nowstock: nowstock
        })
      } else {
        wx.showToast({
          title: '不能大于最大库存',
          icon: "none"
        })
      }
    }
  },
  //加入购物车按钮
  carbtn(e) {
    //是否是拼团购买
    let isGroup = e.currentTarget.dataset.isgroup
    //购买类型  0 直接购买   1VIP购买   2拼团购买
    let buytype = e.currentTarget.dataset.buytype
    console.log(buytype)
    console.log(this.data.isVip)
    checklogin().then((res)=>{
      //如果可以购买 this.data.available
      if (this.data.available){
        this.setData({
          isGroup: isGroup,
          buytype: buytype,
          goodsboxprice: buytype == 0 ? this.data.data.salePriceRange : (buytype == 1 ? this.data.data.vipPriceRange : this.data.data.groupPriceRange)
        })
        let colorchecked = this.data.colorchecked
        let skuchecked = this.data.skuchecked
        let nowstock = this.data.nowstock
        let goodsboxshow = this.data.goodsboxshow
        //弹出选择框
        this.setData({
          goodsboxshow: true,
          maskstate: true
        })
      }
    })
  },
  //计算选中颜色尺码下的库存和规格id
  stockandspecid(){
    let colorchecked = this.data.colorchecked
    let skuchecked = this.data.skuchecked
    let specData = this.data.specData
    let specId
    let checkedstock
    //如果只有颜色，查颜色
    if (colorchecked && !skuchecked){
      specId = specData.find(x => x.color == colorchecked ).specId
      checkedstock = specData.find(x => x.color == colorchecked).stock
    //如果只有尺码，查尺码
    } else if (skuchecked && !colorchecked){
      specId = specData.find(x.skusize == skuchecked).specId
      checkedstock = specData.find( x.skusize == skuchecked).stock
    //颜色尺码都查
    }else{
      specId = specData.find(x => x.color == colorchecked && x.skusize == skuchecked).specId
      checkedstock = specData.find(x => x.color == colorchecked && x.skusize == skuchecked).stock
    }
    this.setData({
      specId: specId,
      checkedstock: checkedstock
    })
    console.log('specId:' + specId, 'checkedstock:'+checkedstock, 'goodsId:' + this.data.goodsId)
  },
  //加购操作
  addtocart(addnum = 1) {
    //清空购物车数据 因为返回上一级后不保存购物车数据
    wx.removeStorageSync('cartGoods')
    //打印缓存数据
    let cartGoods = wx.getStorageSync('cartGoods')
    console.log(cartGoods)
    let goodsId = cartGoods?cartGoods.goodsId.split(','):[]
    let specId = cartGoods ? cartGoods.specId.split(',') : []
    let num = cartGoods ? cartGoods.num.split(',') : []
    let goodsCheck = cartGoods ? cartGoods.goodsCheck.split(',') : []
    console.log(specId)
    //如果有同样规格的商品 在原来数量上增加
    if (specId.includes(this.data.specId)){
      //获取查到对应数据的下标
      let index = specId.findIndex(x => x == this.data.specId)
      console.log(index)
      num[index] = parseInt(num[index]) + addnum
      if (num[index] > parseInt(this.data.checkedstock) )  {
        wx.showToast({
          title: '不能大于最大库存',
          icon: "none"
        })
        return
      }
    //如果没有相同的，就在后面插入一条数据
    }else{
      specId.push(this.data.specId)
      goodsId.push(this.data.goodsId)
      num.push(addnum)
    }
    cartGoods = {
      specId: specId.join(),
      goodsId: goodsId.join(),
      num: num.join(),
      goodsCheck: goodsCheck.join(),
    }
    //设置缓存
    wx.setStorageSync('cartGoods', cartGoods)
    wx.showToast({
      title: '添加成功',
      icon: "none"
    })
    //计算购物车数量
    this.calccartnum()
    wx.navigateTo({
      url: `../../cart/cart?isGroup=${this.data.isGroup}&buytype=${this.data.buytype}`,
    })
  },
  //计算购物车数量
  calccartnum () {
    if (wx.getStorageSync('cartGoods') ){
      let length = wx.getStorageSync('cartGoods') ? wx.getStorageSync('cartGoods').specId.split(',').length : ''
      this.setData({
        cartnum: length
      })
    }
  },
  //立即下单
  topay () {
    this.carbtn(true)
  },
  //关闭商品选择规格弹窗
  closegoodsbox () {
    this.setData({
      goodsboxshow: false,
      maskstate: false
    })
  },
  //确认用户都选择了 并且关闭商品选择规格弹窗
  confirmgoodsbox() {
  if ( (this.data.targetColor.length ? this.data.colorchecked : true ) && ( this.data.targetSkusize.length ? this.data.skuchecked : true) ){
      this.setData({
        goodsboxshow: false,
        maskstate: false
      })
      this.stockandspecid()
      this.addtocart(this.data.nowstock)
    }else{
      wx.showToast({
        title: '请选择颜色尺码',
        icon:"none"
      })
    }
  },
  //打开领取优惠券弹窗
  couponboxshow () {
    this.setData({
      couponboxshow: true,
      maskstate: true
    })
  },
  //关闭领取优惠券弹窗
  closecouponbox () {
    this.setData({
      couponboxshow: false,
      maskstate: false
    })
  },
  //领取优惠券
  getcoupontbn (e) {
    let receive = e.currentTarget.dataset.receive
    let couponid = e.currentTarget.dataset.couponid
    console.log(receive, couponid)
    checklogin().then((res)=>{
      console.log(res)
      //0没领过 可以领    1领过了
      if (receive == 0) {
        axios({
          url: '/coupon/getInSpecial',
          data: {
            couponId: couponid,
            userid: this.data.userid,
            token: this.data.token
          }
        }).then((res) => {
          console.log(res)
          let coupons = this.data.coupons
          coupons.find(x => x.couponId == couponid).receive = 1
          this.setData({
            coupons: coupons
          })
        })
      }else{
        wx.showToast({
          title: '已经领取过了',
          icon:'none'
        })
      }
    })
  },
  //去评价页面
  toappraise () {
    let { goodsId, comment } = this.data
    console.log(goodsId, comment )
    wx.navigateTo({
      url: `appraise/appraise?goodsId=${goodsId}&comment=${comment}`
    })
  },
  //去拼单页面
  gomergeorder (e) {
    let index = e.currentTarget.dataset.index
    let isbuy = e.currentTarget.dataset.isbuy
    console.log(index, isbuy)
    //如果能购买拼单商品
    if (isbuy){
      wx.navigateTo({
        url: `mergeorder/mergeorder?index=${index}`
      })
    }
  },
  //查看拼单商品详情
  gogoodsdetail (e) {
    let goodsid = e.currentTarget.dataset.goodsid
    console.log(goodsid)
    wx.navigateTo({
      url: `/pages/home/goodsDetail/goodsDetail?linkId=${goodsid}`
    })
  },
  //打开服务弹窗
  openservicebox () {
    this.setData({
      servicewindershow: true,
      maskstate: true
    })
  },
  //关闭服务弹窗
  closeservicewinder () {
    this.setData({
      servicewindershow: false,
      maskstate: false
    })
  },
  //去购物车
  // gocart () {
  //   checklogin().then((res) => {
  //     wx.switchTab({
  //       url: '../../cart/cart',
  //     })
  //   })
  // },
  //去会员中心
  govipcenter () {
    checklogin().then((res) => {
      wx.navigateTo({
        url: '../../my/vipcenter/vipcenter',
      })
    })
  },
  //收藏商品
  likegoods () {
    checklogin().then((res)=>{
      let isLike = this.data.data.isLike
      let goodsId = this.data.goodsId
      let data = this.data.data
      console.log(res)
      axios({
        url: '/goods/collectGoods',
        data: {
          userid: res.userid,
          token: res.token,
          type: isLike ? 2 : 1,            //1: 收藏 2：取消收藏
          goodsId: goodsId
        }
      }).then((res) => {
        console.log(res)
        data.isLike = !data.isLike
        this.setData({
          data: data
        })
        if (isLike == 1){
          wx.showToast({
            title: '取消成功',
            icon:"none"
          })
        }else{
          wx.showToast({
            title: '收藏成功',
            icon: "none"
          }) 
        }
      })
    })
  },
  //点击关闭蒙层
  closemask () {
    this.setData({
      maskstate:false,
      servicewindershow:false,
      couponboxshow: false,
      goodsboxshow:false,
      kefustate:false
    })
  },
  //去更多拼团商品页面
  moregroup () {
    console.log(22)
  },
  //拼团购买 去拼团页面
  grouppay () {
      wx.navigateTo({
        url: 'grouppage/grouppage',
      })
  },
  //去品鉴师h5
  gooffical (e) {
    let linkurl = e.currentTarget.dataset.linkurl
    let url = `../../webview/webview?goodsId=${this.data.goodsId}&linkId=${linkurl}`
    wx.navigateTo({
      url: url,
    })
  },
    drawShareImg: function () {
        const ctx = wx.createCanvasContext('shareCanvas')

        ctx.setFillStyle('#FFF2E8')
        ctx.fillRect(0, 0, 375, 300)

        wx.downloadFile({
            url: this.data.data.album[0],
            success: goodsImg => {
                if (goodsImg.statusCode === 200) {
                    ctx.drawImage(goodsImg.tempFilePath, 13, 13, 202, 202)

                    ctx.setFontSize(25)
                    ctx.setFillStyle('#C8431A')
                    ctx.fillText('￥', 240, 98)

                    ctx.setFontSize(36)
                    ctx.fillText(this.data.data.vipPrice, 260, 98)

                    ctx.setFontSize(19)
                    ctx.setFillStyle('#9B9B99')
                    ctx.fillText('￥' + this.data.data.shopPrice, 244, 135)

                    ctx.beginPath()
                    ctx.moveTo(245, 128)
                    ctx.lineTo(263 + 12 * (this.data.data.shopPrice.length), 128)
                    ctx.setStrokeStyle('#9B9B99')
                    ctx.stroke()

                    ctx.setFontSize(17)
                    ctx.setFillStyle('#C8431A')
                    ctx.fillText('好友拼团中', 246, 167)

                    ctx.drawImage('/images/home/shareb2.png', 12.5, 235, 350, 46)

                    ctx.setFontSize(20)
                    ctx.setFillStyle('#fff')
                    ctx.fillText('马上看一看', 132, 265)

                    ctx.drawImage('/images/home/r.png', 237, 250, 18, 17)

                    ctx.draw(true, () => {
                        wx.canvasToTempFilePath({
                            x: 0,
                            y: 0,
                            width: 375,
                            height: 310,
                            canvasId: 'shareCanvas',
                            success: res => {
                                shareImg = res.tempFilePath
                                console.log('shareImg:', shareImg)
                            }
                        })
                    })
                }
            }
        })
    }
})